package com.winai.launcher.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.google.gson.Gson;
import com.ks.projectbasictools.base_interface.StringCallBack;
import com.ks.projectbasictools.okhttp.OkHttpUtils;
import com.ks.projectbasictools.utils.LogUtils;
import com.wang.avi.AVLoadingIndicatorView;
import com.winai.launcher.Application;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.LiveDataBean;
import com.winai.launcher.bean.db.BannerBean;
import com.winai.launcher.bean.db.BannerListBean;
import com.winai.launcher.bean.db.CurrentLocation;
import com.winai.launcher.bean.db.Device;
import com.winai.launcher.bean.requestBean.MainScreenBean;
import com.winai.launcher.bean.responseEntity.BubbleEntity;
import com.winai.launcher.bean.responseEntity.MainScreenEntity;
import com.winai.launcher.bean.responseEntity.MojiEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.HttpUrls;
import com.winai.launcher.constant.MainRouter;
import com.winai.launcher.interfaces.CountTimerListener;
import com.winai.launcher.manager.AiyishengManager;
import com.winai.launcher.manager.DeviceInfoManager;
import com.winai.launcher.manager.DeviceManager;
import com.winai.launcher.manager.LiveManager;
import com.winai.launcher.manager.ScreenProtectManager;
import com.winai.launcher.manager.WeatherManager;
import com.winai.launcher.manager.WindowTipManager;
import com.winai.launcher.override.AlarmCountTimer;
import com.winai.launcher.override.CountTimer;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.service.WeatherService;
import com.winai.launcher.utils.AppExecutors;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.GlideLoadUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.OpenAppUtils;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.utils.UrlUtil;
import com.winai.launcher.utils.WeatherIconUtil;
import com.winai.launcher.view.guide.ConfigWifiActivity;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import okhttp3.Call;

/**
 * 作者：康少
 * 时间：2020/2/28 0028
 * 说明：逻辑中转
 */
public class LogicActivity extends BaseActivity implements Observer {

    /*banner*/
    @BindView(R.id.cl_empty)
    RelativeLayout clEmpty;
    @BindView(R.id.tv_currentTime)
    TextView tvCurrentTime;
    @BindView(R.id.banner)
    BGABanner banner;
    @BindView(R.id.iv_weather)
    ImageView ivWeather;
    @BindView(R.id.tv_temperature)
    TextView tvTemperature;
    @BindView(R.id.iv_loading)
    ImageView ivLoading;
    @BindView(R.id.iv_loading2)
    ImageView ivLoading2;
    @BindView(R.id.cl_weather)
    LinearLayout clWeather;
    @BindView(R.id.ll_live)
    LinearLayout llLive;
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.avi)
    AVLoadingIndicatorView avi;
    @BindView(R.id.tv_bubble)
    TextView tvBubble;
    @BindView(R.id.tv_timer)
    TextView tvTimer;

    /*logic*/
    @BindView(R.id.cl_banner)
    ConstraintLayout clBanner;

    /*logic*/
    private Context mContext = this;
    public final static int RESULT_CODE = 10000;
    private boolean consume = true;
    private boolean isBannerShow = false;
    /*banner*/
    private boolean isLoaded = false;
    private BroadcastListener mBroadcastListener;
    private AlarmReceiver alarmReceiver;
    private Animation loadingAnimation;
    /*download*/
    private boolean weatherLoaded = false;//天气是否加载完成；
    private WeatherService myservice;
    /*广播Action*/
    public static final String ACTION_SHOW_WEATHER_PROGRESS = "com.winai.launcher.ACTION_SHOW_WEATHER_PROGRESS";//展示天气加载中
    public static final String ACTION_WEATHER_NULL = "com.winai.launcher.ACTION_WEATHER_NULL";//展示天气为null
    public static final String ACTION_UPDATE_WEATHER = "com.winai.launcher.ACTION_UPDATE_WEATHER";//更新天气
    private Intent weatherServiceIntent;
    private ServiceConnection connection;
    private int bubbleIndex = 0;
    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtils.d("进入Logic的onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        Application.setHomeActivity(this);
        LiveManager.getInstance(mContext).addObserver(this);
        logic();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtils.d("进入Logic的onResume() isBannerShow = " + isBannerShow);
        if (isBannerShow && canInResume()) {
            startBanner();
            if (ScreenProtectManager.getModel() != ScreenProtectManager.ScreenProtectModel.NULL) {
                CountTimer.restart(mContext);
            }
        }
    }

    /**
     * @date 2020/9/27
     * @desc 判断是否显示无网络Tip
     */
    private void checkWifi() {
        if (!NetworkUtils.hasNetwork(mContext) && isBannerShow) {
            runOnUiThread(() -> WindowTipManager.getInstance(mContext).showTip());
        } else {
            runOnUiThread(() -> WindowTipManager.getInstance(mContext).dismissTip());
        }
    }

    private void logic() {
        //首次打开APP，显示引导页
        DB_Common dbCommon = new DB_Common(this);
        String isFirst = dbCommon.get("isFirstOpenApp");
        LogUtils.e("isFirst = " + isFirst);
        if (TextUtils.isEmpty(isFirst)) {
            //第一次打开设备
            showDownload();
        } else {
            Device device = DeviceManager.loadDeviceFromDB(BaseUtils.getDeviceId());
            LogUtils.d("device != null && device.isBindStatus() =" + (device != null && device.isBindStatus()));
            if (device != null && device.isBindStatus()) {
                dbCommon.add("isBind", "true");
                showBanner();
            } else {
                showCacheBanner(false);//展示缓存Banner
                new Thread(this::setTime).start();//展示时间

                loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
                loadingAnimation.setInterpolator(new LinearInterpolator());
                showWeatherProgressBar();//添加转圈
            }
//            else if (consume) {
//                //设置常量为false，避免重复调用
//                consume = false;
//                /* 跳转客户的激活app */
//                try {
//                    Intent intent = new Intent();
//                    intent.setClassName("com.aiyisheng.speaker"
//                            , "com.aiyisheng.speaker.user.activation.ActivationActivity");
//                    intent.putExtra("deviceId", BaseUtils.getDeviceId());//新增deviceId参数
//                    startActivityForResult(intent, RESULT_CODE);
//                    LogUtils.d("跳转艾益生激活二维码页面，deviceId = " + BaseUtils.getDeviceId());
//                    /*((BaseActivity) mContext).overridePendingTransition(0, 0);*/
//                } catch (Exception e) {
//                    e.printStackTrace();
////                    runOnUiThread(() -> ToastKs.show(mContext, "您还没有安装小艾音箱"));
//                }
//            }
        }
//        checkWifi();
    }

    private void showBanner() {
        NotifyReceiverUtils.notifyLauncherStart(mContext);
        NotifyReceiverUtils.notifyPulldownReceiver(mContext, true);//允许下拉
        NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext, true);//允许唤醒
        NotifyReceiverUtils.notifyAiyishengLogin(mContext.getApplicationContext());//通知ai，艾益生登陆成功
        isBannerShow = true;
        banner.setVisibility(View.VISIBLE);
        banner_initObject();
        banner_initListener();
        showCacheBanner(false);//展示缓存Banner
        bindWeatherService();//绑定天气服务
        new Thread(LogicActivity.this::banner_getWeather).start();//展示天气
        startBanner();
    }

    private void startTimerToUpdateBubble(BubbleEntity bean) {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (bubbleIndex >= bean.getData().size()) {
                            bubbleIndex = 0;
                        }
                        tvBubble.setText(bean.getData().get(bubbleIndex).getContent());
                        bubbleIndex++;
                    }
                });
            }
        }, 0, 60 * 1000);
    }

    private void bindWeatherService() {
        //开始绑定Service
        weatherServiceIntent = new Intent(LogicActivity.this, WeatherService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                LogUtils.e("weatherService连接");
                myservice = ((WeatherService.MyBinder) iBinder).getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                LogUtils.e("weatherService断开");
                myservice = null;
            }
        };
        try {
            mContext.bindService(weatherServiceIntent, connection, Context.BIND_AUTO_CREATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDownload() {
        finish();
        startActivity(new Intent(mContext, ConfigWifiActivity.class));
    }

    private void startBanner() {
        banner_getLiveState(LiveManager.getInstance(mContext).getShouldShowDialog());
        banner_requestMainScreen();
        new Thread(this::setTime).start();
        requestBubble();//请求气泡内容
    }

    /**
     * @date 6/4/21
     * @desc 请求气泡
     */
    private void requestBubble() {
        //请求气泡内容
        OkHttpUtils.requestGet(mContext, getString(R.string.URL_BUBBLE), null, new StringCallBack<BubbleEntity>() {
            @Override
            public void onResponse(BubbleEntity bean, int id) {
                if (bean != null && bean.isSuccess()) {
                    if (bean.getData() != null && bean.getData().size() > 0) {
                        tvBubble.setVisibility(View.VISIBLE);
                        //定时增加index
                        startTimerToUpdateBubble(bean);
                    } else {
                        tvBubble.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    /**
     * -------------------==========   以下是 Banner   ===========----------------------
     */
    private void banner_initObject() {
        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());
        weatherLoaded = weatherLoaded();

        //检查开启悬浮窗权限
        if (!Settings.canDrawOverlays(mContext)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 1234);
        }

        timer = new Timer();
    }

    /**
     * @param showEmpty
     * @desc 展示Banner缓存
     */
    private void showCacheBanner(boolean showEmpty) {
        new Thread(() -> {
            BannerBean bannerBean = LitePal.findLast(BannerBean.class);
            List<BannerListBean> bannerListBeanList = LitePal.findAll(BannerListBean.class);
            if (bannerListBeanList != null) {
                banner_showEmpty(false);
                LogUtils.d("获取缓存的Banner数量" + bannerListBeanList.size());
            } else {
                LogUtils.d("获取缓存的Banner为空");
                if (showEmpty)
                    banner_showEmpty(true);
            }
            if (bannerBean != null && bannerListBeanList != null) {
                runOnUiThread(() -> initBanner(bannerBean, bannerListBeanList));
            }
        }).start();
    }

    private void setTime() {
        while (!Constant.isTimeInited) {
            String currentTime = BaseUtils.getCurrentTime();
            String hhmm = BaseUtils.timeStamp2Date(currentTime, "HH:mm");
            String yymmd = BaseUtils.timeStamp2Date(currentTime, "yyyy-MM-dd");

            LogUtils.e("获取的时间 time = " + yymmd + " " + hhmm);
            if (yymmd.equals("2010-01-01") || yymmd.equals("1970-01-01")) {
                showTimeProgressBar();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                runOnUiThread(() -> tvCurrentTime.setText(hhmm));
                hidingTimeProgressBar();
                Constant.isTimeInited = true;
            }
        }
    }

    private void banner_requestMainScreen() {
        if (!canIn() || !NetworkUtils.hasNetwork(mContext)) {
            return;
        }
        LogUtils.d("请求一次主屏轮播图接口");
        MainScreenBean mainScreenBean = new MainScreenBean();
        OkHttpUtils.requestBodyPost(mContext, HttpUrls.MAIN_SCREEN, mainScreenBean, new StringCallBack<MainScreenEntity>() {
            @Override
            public void onResponse(MainScreenEntity var1, int id) {
                if (var1 == null || var1.getData() == null || var1.getData().getMainScreenVoList() == null
                        || var1.getData().getMainScreenVoList().size() == 0) {
                    showCacheBanner(true);//展示缓存Banner
                } else {
                    cacheBanner(var1);
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
                showCacheBanner(true);//展示缓存Banner
            }
        });
    }

    /**
     * @desc 缓存banner
     */
    private void cacheBanner(MainScreenEntity var1) {
        BannerBean bannerBean = new BannerBean();
        bannerBean.setRotationTime(var1.getData().getCarouselSetVo().getRotationTime());
        bannerBean.setRotationMode(var1.getData().getCarouselSetVo().getRotationMode());
        bannerBean.saveOrUpdate("id = 1");

        LitePal.deleteAll(BannerListBean.class);
        List<BannerListBean> listBeanList = new ArrayList<>();
        List<MainScreenEntity.DataBean.MainScreenVoListBean> mainScreenVoList = var1.getData().getMainScreenVoList();
        for (MainScreenEntity.DataBean.MainScreenVoListBean bean : mainScreenVoList) {
            BannerListBean bannerListBean = new BannerListBean();
            bannerListBean.setPictureName(bean.getPictureName());
            bannerListBean.setPicturePath(bean.getPicturePath());
            bannerListBean.setLink(bean.getLink());
            listBeanList.add(bannerListBean);
        }
        LitePal.saveAll(listBeanList);

        initBanner(bannerBean, listBeanList);
    }

    private long sTime = 0;//请求的时间

    private boolean canIn() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - sTime < 5000) {
            LogUtils.d("5s内限制主屏轮播图接口请求");
            return false;
        }
        sTime = ct;
        return true;
    }

    private long resumeTime = 0;//请求的时间

    private boolean canInResume() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - resumeTime < 5000) {
            LogUtils.d("5s内限制重复进入Logic_OnResume");
            return false;
        }
        resumeTime = ct;
        return true;
    }

    private void initBanner(BannerBean data, List<BannerListBean> listBeanList) {
        banner.setAutoPlayAble(!data.getRotationTime().equals("0"));
        banner.setAutoPlayInterval(Integer.parseInt(data.getRotationTime()) * 1000);
        if (data.getRotationMode().equals("1")) {
            // 倒序排列
            Collections.reverse(listBeanList);
        }

        banner.setAdapter((BGABanner.Adapter<ImageView, BannerListBean>) (banner, itemView, model, position) -> {
            if (model != null) {
                GlideLoadUtils.getInstance().glideLoad(mContext, model.getPicturePath(), itemView);
            }
        });
        banner.setData(listBeanList, null);
        banner.setDelegate((BGABanner.Delegate<ImageView, BannerListBean>) (banner, itemView, model, position) -> {
            if (model != null && !TextUtils.isEmpty(model.getLink()) && model.getLink().contains("ays.speaker.action")) {
                UrlUtil.UrlEntity urlEntity = UrlUtil.parse(model.getLink());
                //跳转艾益生界面
                AiyishengManager.getInstance(mContext)
                        .intentActivity("ays.speaker.action", new Gson().toJson(urlEntity.params), false);
            }
        });
        LogUtils.d("执行完initBanner方法");
    }

    private void banner_initListener() {
        //注册网络监听广播 
        mBroadcastListener = new BroadcastListener();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_NETWORK_STATE_CHANGED);
        filter.addAction(LogicActivity.ACTION_SHOW_WEATHER_PROGRESS);
        filter.addAction(LogicActivity.ACTION_WEATHER_NULL);
        filter.addAction(LogicActivity.ACTION_UPDATE_WEATHER);
        registerReceiver(mBroadcastListener, filter);

        alarmReceiver = new AlarmReceiver();
        alarmReceiver.register(mContext);

        //时钟广播—— 一分钟更新一次
        IntentFilter filter2 = new IntentFilter();
        filter2.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(banner_timeReceiver, filter2);

        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.WEATHER_UPDATE:
                        //更新天气信息
                        MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
                        if (mojiEntity != null) {
                            banner_updateViewData(mojiEntity);
                        }
                        break;
                }

            }
        });
    }

    private void banner_getLiveState(Integer liveState) {
        LiveDataBean liveDataBean = LiveManager.getInstance(mContext).getLiveDataBean();
        String teacherAvatar = "";
        if (liveDataBean != null) {
            teacherAvatar = liveDataBean.getTeacherAvatar();
        }
        LogUtils.d("shouldShowDialog = " + liveState + ";teacherAvatar = " + teacherAvatar);
        switch (liveState) {
            case LiveManager.SHOW_WHITE:
                toggleLiveState("white");
                break;
            case LiveManager.SHOW_GREEN:
                toggleLiveState("green");
                break;
            case LiveManager.NOT_SHOW:
                toggleLiveState("not_show");
                break;
        }
    }

    private void toggleLiveState(String state) {
        runOnUiThread(() -> {
            switch (state) {
                case "white":
                    llLive.setVisibility(View.VISIBLE);
                    avi.setIndicatorColor(getResources().getColor(R.color.colorWhite));
                    avi.show();
                    PicassoLoadUtils.getInstance().picassoLoad(LiveManager.getInstance(mContext).getLiveDataBean().getTeacherAvatar()
                            , ivHeader
                            , R.mipmap.icon_live_head
                            , 100);
                    break;
                case "green":
                    llLive.setVisibility(View.VISIBLE);
                    avi.setIndicatorColor(getResources().getColor(R.color.colorGreen));
                    avi.show();
                    PicassoLoadUtils.getInstance().picassoLoad(LiveManager.getInstance(mContext).getLiveDataBean().getTeacherAvatar()
                            , ivHeader
                            , R.mipmap.icon_live_head
                            , 100);
                    break;
                case "not_show":
                    llLive.setVisibility(View.GONE);
                    avi.hide();
                    break;
            }
        });
    }

    private void banner_showEmpty(boolean showEmpty) {
        isLoaded = !showEmpty;
        runOnUiThread(() -> {
            clEmpty.setVisibility(showEmpty ? View.VISIBLE : View.GONE);
            banner.setVisibility(showEmpty ? View.GONE : View.VISIBLE);
        });
    }

    private int count = 0;

    /**
     * 说明：获取天气信息
     */
    private void banner_getWeather() {
        while (!weatherLoaded && count < 5) {
            try {
                count++;
                LogUtils.d("第" + count + "次获取天气");
                WeatherManager.getInstance(mContext).requestWeatherData();
                Thread.sleep(3000);
                weatherLoaded = weatherLoaded();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (count >= 5 && !weatherLoaded) {
            hidingWeatherProgressBar();
            CurrentLocation last = LitePal.findLast(CurrentLocation.class);
            String adminArea = last.getAdminArea().replace("市", "");
            String locality = last.getLocality().contains("市") ? last.getLocality() : last.getLocality() + "市";
            runOnUiThread(() -> {
                Toast.makeText(mContext, "天气获取失败:" + adminArea + "," + locality, Toast.LENGTH_SHORT).show();
                tvTemperature.setText("--℃");
                PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName("999")
                        , ivWeather);
            });
        }
    }

    private boolean weatherLoaded() {
        CurrentLocation last = LitePal.findLast(CurrentLocation.class);
        //更新天气信息
        MojiEntity mojiEntity = WeatherManager.getInstance(mContext).getMojiEntity();
        if (last != null && mojiEntity != null) {
            LogUtils.e("weatherDuiBean.getCityName()： " + mojiEntity.getCity()
                    + "，last.getLocality()：" + last.getLocality());
            if (mojiEntity.getCity().contains(last.getLocality())) {
                banner_updateViewData(mojiEntity);
            } else {
                //非本地位置，不更新
                LogUtils.e("非当前定位的位置，轮播图界面不更新天气数据");
            }
            return true;
        } else {
            showWeatherProgressBar();
            return false;
        }
    }

    @SuppressLint("SetTextI18n")
    private void banner_updateViewData(MojiEntity mojiEntity) {
        hidingWeatherProgressBar();
        runOnUiThread(() -> {
            tvTemperature.setText(mojiEntity.getCondition().getTemp() + "℃");
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName(mojiEntity.getCondition().getCondition())
                    , ivWeather);
        });
    }

    /**
     * @date 2020/10/9
     * @desc 时间加载中…
     */
    public void showTimeProgressBar() {
        runOnUiThread(() -> {
            if (ivLoading.getVisibility() == View.VISIBLE) {
                return;
            }
            ivLoading.setVisibility(View.VISIBLE);
            tvCurrentTime.setVisibility(View.INVISIBLE);
            ivLoading.startAnimation(loadingAnimation);
        });
    }

    /**
     * @date 2020/10/9
     * @desc 隐藏时间加载中
     */
    public void hidingTimeProgressBar() {
        runOnUiThread(() -> {
            ivLoading.setVisibility(View.GONE);
            tvCurrentTime.setVisibility(View.VISIBLE);
            ivLoading.clearAnimation();
        });
    }

    /**
     * @date 2020/10/9
     * @desc 天气加载中……
     */
    public void showWeatherProgressBar() {
        runOnUiThread(() -> {
            ivLoading2.setVisibility(View.VISIBLE);
            clWeather.setVisibility(View.INVISIBLE);
            ivLoading2.startAnimation(loadingAnimation);
        });
    }

    /**
     * @date 2020/10/9
     * @desc 隐藏天气
     */
    public void hidingWeatherProgressBar() {
        runOnUiThread(() -> {
            ivLoading2.setVisibility(View.GONE);
            clWeather.setVisibility(View.VISIBLE);
            ivLoading2.clearAnimation();
        });
    }

    /**
     * 说明：一分钟监听更新一次UI
     */
    private final BroadcastReceiver banner_timeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null && action.equals(Intent.ACTION_TIME_TICK)) {
                AppExecutors.getInstance().networkIO().execute(() -> {
                    String ss = BaseUtils.getInitTime();
                    String hhmm = BaseUtils.timeStamp2Date(ss, "HH:mm");
                    AppExecutors.getInstance().mainThread().execute(() -> tvCurrentTime.setText(hhmm));
                });
            }
        }
    };

    @Override
    public void update(Observable observable, Object o) {
        if (o instanceof Integer) {
            banner_getLiveState((Integer) o);
        }
    }

    private class AlarmReceiver extends BroadcastReceiver {
        public void register(Context mContext) {
            /**
             * 异步搜索蓝牙设备——广播接收
             */
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.action_alarm);// 找到设备的广播
            // 注册广播
            mContext.getApplicationContext().registerReceiver(AlarmReceiver.this, filter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到的广播类型
            String action = intent.getAction();
            if (action != null && action.equals(Constant.action_alarm)) {
                // * @param isHasAlarm 是否显示闹钟图标
                // * @param isCountdown 是否显示稍后提醒倒计时
                boolean isHasAlarm = intent.getBooleanExtra("isHasAlarm", false);
                boolean isCountdown = intent.getBooleanExtra("isCountdown", false);
                long nextRingTime = intent.getLongExtra("nextRingTime", 0);//下次响铃的时间戳-毫秒
                LogUtils.d("接收到艾益生闹钟广播：isHasAlarm = " + isHasAlarm
                        + ";isCountdown = " + isCountdown
                        + ";nextRingTime = " + nextRingTime);
                tvTimer.setVisibility(isHasAlarm ? View.VISIBLE : View.GONE);
                if (isCountdown && nextRingTime != 0) {
                    AlarmCountTimer.start((int) ((nextRingTime - System.currentTimeMillis()) / 1000), new CountTimerListener() {
                        @Override
                        public void onFinish() {
                            tvTimer.setVisibility(View.GONE);
                        }

                        @Override
                        public void onTick(long millisUntilFinished) {
                            tvTimer.setVisibility(View.VISIBLE);
                            tvTimer.setText(BaseUtils.timeStamp2Date(String.valueOf(millisUntilFinished / 1000), "mm:ss"));
                        }
                    });
                } else {
                    AlarmCountTimer.release();
                    tvTimer.setText("");
                }
            }
        }
    }

    /**
     * 作者：康少
     * 时间：2020/3/18 0018
     * 说明：网络监听
     */
    public class BroadcastListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                switch (action) {
                    case Constant.ACTION_NETWORK_STATE_CHANGED:
                        boolean hasNetwork = intent.getBooleanExtra("hasNetwork", false);
                        LogUtils.d("<<<============主轮播图网络监听==========>>> hasNetwork = " + hasNetwork);
                        if (hasNetwork) {
                            if (myservice != null) {
                                new Thread(() -> myservice.banner_getWeather(mContext)).start();
                            }
                            requestBubble();//请求气泡内容
                        }
                        break;
                    case LogicActivity.ACTION_SHOW_WEATHER_PROGRESS:
                        boolean showWeatherProgressBar = intent.getBooleanExtra("showWeatherProgressBar", false);
                        if (showWeatherProgressBar) {
                            showWeatherProgressBar();
                        } else {
                            hidingWeatherProgressBar();
                        }
                        break;
                    case LogicActivity.ACTION_UPDATE_WEATHER:
                        MojiEntity mojiEntity = (MojiEntity) intent.getSerializableExtra("mojiEntity");
                        if (mojiEntity != null) {
                            banner_updateViewData(mojiEntity);
                        }
                        break;
                    case LogicActivity.ACTION_WEATHER_NULL:
                        boolean weatherNull = intent.getBooleanExtra("weatherNull", true);
                        if (weatherNull) {
                            tvTemperature.setText("--℃");
                            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(WeatherIconUtil.getImgByName("999")
                                    , ivWeather);
                        }
                        break;
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        consume = true;
        Constant.isTimeInited = false;//防止onResume的时候时间不显示
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(banner_timeReceiver);
            unregisterReceiver(mBroadcastListener);
            unregisterReceiver(alarmReceiver);
        } catch (IllegalArgumentException e) {
            //LogUtils.e("捕捉一个crash ScreenProtectActivity unregisterReceiver(receiver)");
        }
        if (connection != null) {
            unbindService(connection);
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 说明：勿删！！
     *
     * @return true 放开上滑返回手势，默认true
     */
    public boolean isAllowCustomSliding() {
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RESULT_CODE:
                    if (data != null) {
                        long userId = data.getLongExtra("userId", 0);
                        AppExecutors.getInstance().networkIO().execute(new Runnable() {
                            @Override
                            public void run() {
                                // 更新设备最近绑定状态
                                DeviceInfoManager.getInstance(mContext).updateBind(
                                        BaseUtils.timeStamp2Date(BaseUtils.getInitTime(), "")
                                        , String.valueOf(userId)
                                );
                            }
                        });
                        showBanner();
                        LogUtils.e("激活返回成功，显示Banner");
                    } else {
                        LogUtils.e("激活返回的data为 null");
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.iv_menu, R.id.cl_empty, R.id.cl_weather, R.id.ll_live, R.id.tv_timer, R.id.tv_currentTime})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_menu:
                startActivity(new Intent(mContext, MainActivity.class));
                break;
            case R.id.cl_empty:
                banner_requestMainScreen();
                break;
            case R.id.cl_weather:
                startActivity(new Intent(mContext, WeatherActivity.class));
                break;
            case R.id.ll_live:
                OpenAppUtils.startIntentPath(mContext, LiveManager.getInstance(mContext).getRouterPath(), ".名师直播@");
                break;
            case R.id.tv_timer:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_SETTING_ALARM, ".闹钟@");
                break;
            case R.id.tv_currentTime:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_SETTING_CLOCK, ".时钟@");
                break;
        }
    }
}
